<template>
  <div class="main">
    <!--    顶部导航条-->
    <navheader></navheader>
    <!--    主体内容-->
    <div class="container-fluid discussion_main">
      <!--      上部内容-->
      <div class="top_main">
        <!--      图片背景部分-->
        <div class="jumbotron">
          <div class="text-white">
            <div class="d-lg-flex align-items-center justify-content-between text-center pl-lg-5"  style="margin-top:30px;">
              <div class="col pt-5" >
                <h1 class="title">愿 所 有 为 梦 想 而 战 的 考 研 “嘉” 人</h1>
                  <h1 class="pt-2">风 起 扬 帆 ，上 岸，不 留 遗 憾！</h1>

                <div class="row pt-4" style="padding-left:400px">
                  <div class="col-md-2" >
                    <select class="yearsfontclass form-control form-control-placeholder" v-model="year" @change="selectChange_year($event)">
                      <option value="2024" style="color: black;">2024</option>
                      <option value="2025" style="color: black;">2025</option>
                      <option value="2026" style="color: black;">2026</option>
                    </select>
                  </div>
                  <div class="col-md-6 pt-1" style="margin-left: -70px">
                    <h5 style="font-weight: bold;font-size: 30px">年考研倒计时 {{days}} 天</h5>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <!--      头像-->
          <div class="col-md-3 col-sm-3">
            <div class="user_img" style="background-color: white;width:250px;height: 250px;padding: 7px;border-radius: 7px;">
              <img :src="this.show_user_img" alt="" style="width:250px;height: 250px;border-radius: 7px;">
            </div>
          </div>
          <div class="col-md-5 ml-5 col-sm-5">
            <div class="" style="margin-top: -170px">
              <!--        用户名-->
              <h5 style="font-size: 40px">{{showUserName}}</h5>
              <div class="row mt-3 ml-1">
                <div class="infoclassfont">{{this.user_info.sex}}</div>
                <div class="ml-2" style="background-color:#3f7e74;width: 3px;height: 28px"></div>
                <div class="infoclassfont pl-2">{{this.user_info.city}}</div>
                <div class="ml-2" style="background-color:#3f7e74;width: 3px;height: 28px"></div>
                <div class="infoclassfont pl-2">{{this.user_info.email}}</div>
                <div class="ml-2" style="background-color:#3f7e74;width: 3px;height: 28px"></div>
                <div class="infoclassfont pl-2">{{this.user_info.birthday}}</div>
                <div class="ml-2" style="background-color:#3f7e74;width: 3px;height: 28px"></div>
                <div class="infoclassfont pl-2" v-if="this.user_info.identity==0">学生</div>
                <div class="infoclassfont pl-2" v-if="this.user_info.identity==1">已毕业的学长学姐</div>
                <div class="infoclassfont pl-2" v-if="this.user_info.identity==2">老师</div>
                <div class="ml-2" style="background-color:#3f7e74;width: 3px;height: 28px"></div>
              </div>
            </div>
          </div>
          <!--      修改资料按钮-->
          <div class="col-md-4 col-sm-4" style="margin-top: -120px;margin-left: 1100px">
            <el-button type="primary" @click="openUpdate"
                       icon="el-icon-edit" >我要发贴</el-button>
            <el-button type="primary" plain
                       class="daily_bonus"
                       @click="click_daily_bonus"
                       :class="[daily_bonus_click_able?'can_clicked':'clicked']"
                       icon="el-icon-medal-1" >
              {{this.daily_bonus_text}}
            </el-button>

<!--            发布帖子 弹窗内容-->
            <el-dialog title="发布帖子" :visible.sync="dialogFormVisible" @close="handleClose">

              <el-form :model="form" :rules="rules" :before-close="closeDiv" ref="form" label-width="100px" class="form" status-icon >

                <el-form-item label="帖子标题" :label-width="formLabelWidth" prop="post_title">
                  <el-input v-model="form.post_title"
                            type="text"
                            maxlength="20"
                            autocomplete="off"
                            show-word-limit
                            placeholder="请输入帖子标题，3-20个字符...">
                  </el-input>
                </el-form-item>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="帖子类别" :label-width="formLabelWidth" prop="post_category">
                      <el-select v-model="form.post_category" placeholder="选择帖子类别...">
                        <el-option label="求助问答" value="1"></el-option>
                        <el-option label="学长学姐经验贴" value="2"></el-option>
                        <el-option label="日常生活" value="3"></el-option>
                        <el-option label="其他" value="4"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="帖子标签" :label-width="formLabelWidth" prop="post_label">
                      <el-input v-model="form.post_label"
                                type="text"
                                maxlength="20"
                                autocomplete="off"
                                show-word-limit
                                placeholder="请输入帖子标签，3-20个字符...">
                      </el-input>
                    </el-form-item>
                  </el-col>

                </el-row>

                <el-form-item label="帖子内容" :label-width="formLabelWidth" prop="post_content">
                  <el-input
                      show-word-limit
                      type="textarea"
                      maxlength="2000"
                      :rows="10"
                      placeholder="请输入内容，1-2000个字符"
                      v-model="form.post_content">
                  </el-input>
                </el-form-item>

                <el-form-item label="图片" :label-width="formLabelWidth" prop="post_img">

                  <el-upload ref="upload"
                             name="upload"
                             action="#"
                             drag
                             :file-list="fileList"
                             list-type="picture"
                             :limit="1"
                             :on-exceed="handleExceed"
                             :auto-upload="false"
                             :on-remove="handleRemove"
                             :on-change="imgChange">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>

                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="submitForm('form')">发 布</el-button>
                  <el-button @click="resetForm('form')">重 置</el-button>
                  <el-button @click="cancel()">取 消</el-button>
                </el-form-item>

              </el-form>

            </el-dialog>



          </div>
        </div>
      </div>
      <!--      下部内容-->
      <div class="row bottom_main">
        <router-view></router-view>
      </div>


    </div>
    <!--    底部导航条-->
    <myfooter></myfooter>
  </div>
</template>

<script>
import myfooter from '../../myfooter'
import navheader from '../../navheader'
import Cookies from "js-cookie";
import {getUser_Basic,clockByUser,checkClock} from "@/api/User";


export default {
  name: "discussion_frame",
  components:{
    myfooter,
    navheader,
  },
  data() {
    return {
      param: {
        key: '',
        page: 1,
        limit: 5,
      },
      showUserName:'',
      user_info:{
        user_name:'',
        birthday:'',
        city:'',
        email:'',
        hobby:'',
        profile:'',
        sex:'',
        credit:'',
        identity:'',
        img:'',
        ifcheck:'',

      },
      show_user_img:'',

      //弹窗 发表帖子
      dialogFormVisible: false,
      form: {
        post_title: '',
        post_content: '',
        post_category: '',
        post_label: '',
        post_img:'',
        // post_ctr:'',
        // post_like:''
      },
      //表单校验规则
      rules: {
        post_title: [
          { required: true, message: '请输入帖子标题', trigger: 'blur'},
          { min:3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        post_label: [
          { message: '请输入帖子标签', trigger: 'blur'},
          { min:1, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        post_category: [
          { required: true, message: '请选择帖子类别', trigger: 'change'}
        ],
        post_content: [
          { required: true, message: '请输入帖子内容', trigger: 'blur'},
          { min:1, max: 2000, message: '长度在 1 到 2000 个字符', trigger: 'blur'}
        ]

      },
      formLabelWidth: '120px',
      //文件上传相关
      fileList:[],
      file:[],
      //  倒计时时间相关
      year:2024,
      days:0,
    //  签到相关
      daily_bonus_text: '签到',
      daily_bonus_click_able: true,//【签到】按钮是否可以点击

    }
  },
  methods:{
    // 获取当前用户个人信息
    init(){

      getUser_Basic({
        // token:window.sessionStorage.getItem('token')
      }).then(res=>{
        this.user_info.user_id=res.data.user_id;
        this.user_info.user_name=res.data.username;
        this.user_info.birthday=res.data.birthday;
        this.user_info.city=res.data.city;
        this.user_info.email=res.data.email;
        this.user_info.hobby=res.data.hobby;
        this.user_info.profile=res.data.profile;
        this.user_info.sex=res.data.sex;
        this.user_info.credit=res.data.credit;
        this.user_info.img=res.data.img;
        this.show_user_img='/api/storage/user_img/' + this.user_info.img;

        this.user_info.identity=res.data.identity;
        this.user_info.ifcheck=res.data.ifcheck;
      });

    },
    selectChange_year(event){
      this.year=event.target.value;
      this.getDays();
    },
    //计算倒计时天数  12月24考试
    getDays(){
      var startdate = new Date();  //开始日期，当前日期
      var year = this.year-1; // 选择的年
      var enddate=new Date(`${year}`+'-12-24');
      this.days=parseInt(Math.abs(enddate.getTime() - startdate.getTime()) / 1000 / 60 / 60 / 24);
    },
    //打开发布帖子的弹窗
    openUpdate(){
      if(this.user_info.ifcheck!=1 ){
        this.$msg.error("未通过身份审核不可发贴！");
        return false;
      }
      else{
        this.dialogFormVisible=true;
      }
    },
    getCurrentName(){
      this.showUserName= Cookies.get('currentUserName');
      window.personalCenterCurrentName = this.getCurrentName;
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    //  清空发布的弹窗的内容 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$refs.upload.clearFiles();
      this.fileList=[];
    },
    //添加数据
    async addSave()
    {
      if(this.form.post_category==2 && this.user_info.identity!=1){
        this.$msg.error("只有通过审核的学长学姐可发布经验贴！");
        this.resetForm('form');
        this.dialogFormVisible=false;
        return false;
      }
      let formData = new FormData();
      // alert(this.fileList.length);
      //没有上传图片
      if(this.fileList.length==0){
        formData.append('if_img',0);
      }
      //上传了图片
      else {
        formData.append('if_img',1);
        formData.append('post_img', this.fileList[0].raw);
      }

      formData.append('user_token', window.sessionStorage.getItem('token'));
      formData.append('post_title',this.form.post_title);
      formData.append('post_content',this.form.post_content);
      formData.append('post_category',this.form.post_category);
      formData.append('post_label',this.form.post_label);


      this.$ajax({
        url: "/api/Post/addPost",
        method: "post",
        dataType:'text',
        cache:  false , //上传文件无需缓存
        processData:  false , //用于对data参数进行序列化处理 这里必须false
        contentType:  false ,  //
        data: formData
      }).then((result)=>{

          if (result.data.code == 1) {
            this.$msg.success("发布成功，等待管理员审核！");
          }
          else {
            this.$msg.error('发布失败！');
          }

      });

      this.$refs.upload.clearFiles();
      this.dialogFormVisible=false;
      this.init();

    },
    //发布
    submitForm(formName) {
      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //再次确认
          this.$confirm('确认发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.addSave();
          }).catch(() => {
            this.$msg.error("发布失败！");
          });

        } else {
          this.$msg.error("取消发布！");
          return false;
        }
      });
    },
    //  关闭弹窗
    cancel() {
      this.dialogFormVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
      this.$refs.upload.clearFiles();
      this.fileList=[];

    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$refs.upload.clearFiles();
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
      this.fileList=[];

    },
    handleClose(){
      this.$refs.upload.clearFiles();
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["form"].resetFields();
      });
      this.fileList=[];
    },
    //  文件上传相关
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      fileList=[];
      fileList.length=0;
      this.$refs.upload.clearFiles();
    },
    //  点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //限制上传数量
    handleExceed (file, fileList) {
      this.$msg.warning('只能上传一张图片！');
    },
    //限制用户上传的图片格式和大小。
    imgChange (file,fileList) {

      this.fileList = fileList;
      var img_type = file.name.substring(file.name.lastIndexOf('.') + 1)
      var imgSize = file.size;
      var img_maxsize = 1024 * 500;

      // console.log(img_type == 'jpg');

      if ((img_type != 'jpg') && (img_type != 'png') && (img_type != 'JPG') && (img_type != 'JPEG') && (img_type != 'jpeg')) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片只能是JPG或PNG或JPEG格式!');
        return false;
      }

      if (imgSize>img_maxsize) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片大小不能超过500KB!');
        return false;
      }

      return true;

    },
  //  签到
    click_daily_bonus() {

      //若正在ajax中/已签到
      if ((this.daily_bonus_click_able === false) ){
        this.$message.warning('今日已签到啦!');
        return;
      }
      //禁止再次点击【签到】按钮（防止用户手速过快，重复点击）
      this.daily_bonus_click_able = false;

      clockByUser({
        // token:window.sessionStorage.getItem('token')
      }).then(res=>{
        if (res.data.code==1) {
          this.$message.success('签到成功！积分+10');
          this.daily_bonus_text = "已签到";
          //缓存本次查询结果。今天不用再次查询数据库，减小服务器压力。
          window.sessionStorage.setItem('last_daily_bonus_date',res.data.return_day);
        } else {
          this.daily_bonus_click_able = true;//允许再次签到
        }

      });

    },


  },
  computed:{
    //最后一天签到的日期是不是今天。
    if_today_daily_bonus_local(){
      console.log(window.sessionStorage.getItem('last_daily_bonus_date'));
      //获取本地储存
      let last_daily_bonus_date = Date.parse(window.sessionStorage.getItem('last_daily_bonus_date'));
      //获取今天日期
      let date = new Date();
      let month = date.getMonth()+1;
      let current_date = date.getFullYear()+"/"+ month +"/"+date.getDate()+" 08:00:00";
      let today = Date.parse(current_date);
      //判断是否相等
      if(last_daily_bonus_date === today){
        return true;
      }
      else{
        return false;
      }
    }


  },
  //computed ->created ->mounted
  /// 该步骤在 data 数据实例化之后
  mounted(){

    console.log(window.sessionStorage.getItem('last_daily_bonus_date'));
    //若本地没有签到的记录，或者签到的日期不是今天。则向接口发送AJAX请求。
    if(window.sessionStorage.getItem('last_daily_bonus_date')===null || this.if_today_daily_bonus_local===false){
      //查询当前登录用户，今天是否签到。
      checkClock({
        // token:window.sessionStorage.getItem('token'),
      }).then(res=>{
        console.log(res.data.code)
        //已签到
        if(res.data.code == 1){
          this.daily_bonus_click_able = false;
          this.daily_bonus_text = "已签到";
          //缓存本次查询结果。今天不用再次查询数据库，减小服务器压力。
          window.sessionStorage.setItem('last_daily_bonus_date',res.data.clicked_time);
        }
        else{
          this.daily_bonus_click_able = true;//插入失败，允许再次尝试签到
        }
        // this.daily_bonus_ajaxing = false;//ajax结束
      });

    }
    else
    {
      this.daily_bonus_text = "已签到";
      this.daily_bonus_click_able = false;
    }



  },
  //// 该步骤在 data() 数据实例化之前
  created() {

    let _this=this;
    _this.getCurrentName();
    _this.getDays();
    _this.init();

  }
}
</script>

<style scoped>
.main{
  background: url('~@/assets/discussion/back.jpg') no-repeat center;
  background-size:cover;
  width: 100%;
  background-attachment:fixed;
}
/*上面部分盒子*/
.jumbotron
{
  background: url('~@/assets/discussion_top_back.jpg') no-repeat center;
  background-size:cover;
  height: 600px;
  margin-top:120px;
  margin-right: 100px;
  margin-left: 100px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

}
/*头像*/
.user_img{
  margin-top:-350px;
  margin-left: 150px;
  overflow: hidden;
}
/*选择年份输入框样式设置*/
.yearsfontclass{
  background-color: transparent;
  color: white;
  font-size: 22px;
  font-weight: bold;
}
.infoclassfont{
  font-size: 20px;
  color: #5b5b5b;
}
.main{
  background-attachment:fixed;
}
</style>
